package com.mr.shop.business.impl;

import com.baidu.shop.dto.UserInfo;
import com.baidu.shop.entity.UserEntity;
import com.baidu.shop.utils.BCryptUtil;
import com.baidu.shop.utils.JwtUtils;
import com.mr.shop.business.UserOauthService;
import com.mr.shop.config.JwtConfig;
import com.mr.shop.mapper.UserOauthMapper;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description:
 * @ClassName: UserOauthServiceImpl
 * @Author: User
 * @date: 2020.10.15 17:53
 * @version: 1.0
 */
@Service
public class UserOauthServiceImpl implements UserOauthService {
    @Resource
    private UserOauthMapper mapper;

    @Override
    public String checkUser(UserEntity userEntity, JwtConfig jwtConfig) {
        String token = null;
        Example example = new Example(UserEntity.class);
        example.createCriteria().andEqualTo("username",userEntity.getUsername());
        List<UserEntity> userEntities = mapper.selectByExample(example);
        if (!userEntities.isEmpty()){
            if(BCryptUtil.checkpw(userEntity.getPassword(), userEntities.get(0).getPassword())){
                try {
                    token = JwtUtils.generateToken(new UserInfo(userEntities.get(0).getId(), userEntities.get(0).getUsername()), jwtConfig.getPrivateKey(), jwtConfig.getExpire());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return  token;
    }
}
